package com.wk.gray;

import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 使用AOP获取用户请求头中的参数，并匹配metadata
 */
@Aspect
@Component
public class RequestAspect {

	//定位到要过滤的controller
	@Pointcut("execution(* com.wk.controller..*(..))")
	private void pointcut(){}

	//方法执行前获取请求参数
	@Before(value = "pointcut()")
	public void before(JoinPoint point) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String version = request.getHeader("version");

		//匹配灰度规则的地方，查DB、Redis等
		if (version.trim().equals("v1")) {
			//version是Eureka自定义metadata的key，v1是value
			RibbonFilterContextHolder.getCurrentContext().add("version", "v1");
		}

		//将请求参数放入到ThreadLocal
		//RibbonParameters.set(Collections.singletonMap("version", version));
	}
}
